package cn.wenhaha.common.config;

import cn.wenhaha.common.db.DynamicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;

import javax.sql.DataSource;

/**
 * 数据源
 * --------
 *
 * @author ：wyndem
 * @Date ：Created in 2022-03-19 13:51
 */
@Configuration
public class HikariDbSourceConfig {


    @Bean
    public DataSource dataSource(DynamicDataSource dynamicDataSource) {
        return dynamicDataSource;
    }



    /**
     * 设置数据源代理
     */
    @Bean
    public TransactionAwareDataSourceProxy transactionAwareDataSourceProxy(DataSource dataSource) {
        TransactionAwareDataSourceProxy transactionAwareDataSourceProxy = new TransactionAwareDataSourceProxy();
        transactionAwareDataSourceProxy.setTargetDataSource(dataSource);
        return transactionAwareDataSourceProxy;
    }



    /**
     * 设置事务管理
     */
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(TransactionAwareDataSourceProxy transactionAwareDataSourceProxy) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(transactionAwareDataSourceProxy);
        return dataSourceTransactionManager;
    }

}
